#include <QtGui>
#include <QtXml>
#include "importwidget.h"
#include "openfilebutton.h"
#include "structwidget.h"

ImportWidget::ImportWidget()
{
	setupUi(this);
	_dbase = 0;
	_ofb = new OpenFileButton(tbSelectFile,editFileName,trUtf8("csv (*.csv)"));
	labInfo->setText(QString());
	
	QMenu *menu = new QMenu();
	connect(menu->addAction(trUtf8("Открыть в новом окне")),SIGNAL(triggered()),SLOT(insertsInNewWindow()));
	connect(menu->addAction(trUtf8("Сохранить в файл")),SIGNAL(triggered()),SLOT(insertsInFile()));
	connect(menu->addAction(trUtf8("Отправить на сервер")),SIGNAL(triggered()),SLOT(insertsInServer()));
	pbCreateInsert->setMenu(menu);
}

ImportWidget::~ImportWidget()
{
	qDebug() << Q_FUNC_INFO;
	delete _ofb;
	_ofb = 0;
}
void ImportWidget::on_pbLoad_clicked()
{
	loadFile(editFileName->text());
}

void ImportWidget::loadFile(const QString &fname)
{
	labInfo->setText(QString());
	if(editDelim->text().count()>0) reader.setDelimiter(editDelim->text()[0]);
	if(reader.open(fname)){
		
		editCubeName->setText(cubeNameFromReader());
		
		int row=0;
		twData->setColumnCount(reader.columns().count());
		twData->setRowCount(0);		
		while(reader.next()){						
			int col=0;
			twData->setRowCount(twData->rowCount()+1);
			foreach(QString s,reader.data()){				
				QTableWidgetItem *item = new QTableWidgetItem(s);
				twData->setItem(row,col,item);				
				col++;
			}
			
			row++;
			if(row>=100){
				labInfo->setText(trUtf8("Показаны первые 100 строк."));
				break;
			}
		}
		
	}
}

void ImportWidget::on_editFileName_textChanged(const QString &text)
{
	//loadFile(text);
}

void ImportWidget::selectFile()
{
	tbSelectFile->click();
}

void ImportWidget::on_pbCreateStruct_clicked()
{
	qDebug() << Q_FUNC_INFO << "start";
	
	QString fname = QFileDialog::getSaveFileName(this,trUtf8("Сохранить"),"",STRUCT_PROJ_FILENAME_FILTER);
	if(fname.isEmpty()) return;
	
	QFile file(fname);
	if(!file.open(QIODevice::WriteOnly)){
		QMessageBox::warning(this,trUtf8("Ошибка"),trUtf8("Ошибка открытия файла '%1' для записи").arg(file.fileName()));
		return;
	}
	qDebug() << Q_FUNC_INFO << "x1";
	QDomDocument doc = databaseStruct();
	
	file.write(doc.toString().toUtf8());
	file.close();	
}


QDomElement ImportWidget::createElement(const QString &name,const QString &value)
{
	QDomDocument doc;
	QDomElement root = doc.createElement(name);
	QDomText text = doc.createTextNode(value);
	root.appendChild(text);
	return root;
}

QDomDocument ImportWidget::databaseStruct()
{
	qDebug() << Q_FUNC_INFO << "start";
	QDomDocument doc;
	QString name = cubeName();
	qDebug() << Q_FUNC_INFO << name;
	QDomElement root = doc.createElement("dbstruct");
	doc.appendChild(root);
	QDomElement props = doc.createElement("props");	
	props.setAttribute("alias",name);
	props.setAttribute("name",name);
	root.appendChild(props);
	
	QDomElement stage1 = doc.createElement("stage1");
	root.appendChild(stage1);
	QStringList cols = reader.columns();
	int order=1;
	if(cbFirstAsSepCrd->checkState()==Qt::Checked){
		cols.push_front("uin");
	}
	foreach(QString col,cols){
		QDomElement attr = doc.createElement("attribute");
		attr.setAttribute("name",col);
		
		attr.appendChild(createElement("id",col));
		attr.appendChild(createElement("type","string"));
		attr.appendChild(createElement("order",QString::number(order)));
		attr.appendChild(createElement("length","255"));
		attr.appendChild(createElement("idconf","1"));
		attr.appendChild(createElement("opened","1"));		
		stage1.appendChild(attr);
		order++;
	}
	
	QDomElement stage2 = doc.createElement("stage2");
	root.appendChild(stage2);
	QDomElement stage3 = doc.createElement("stage3");
	root.appendChild(stage3);

	QDomElement cube = doc.createElement("item");
	stage3.appendChild(cube);
	cube.setAttribute("order","0");
	cube.setAttribute("dalias",name);
	cube.setAttribute("name",name);
	
	
	QDomElement dominant = doc.createElement("item");
	cube.appendChild(dominant);	
	dominant.setAttribute("order","1");
	order=2;
	foreach(QString col,cols){
		QDomElement attr = doc.createElement("item");
		attr.setAttribute("order",QString::number(order));
		dominant.appendChild(attr);
		order++;
	}
	
	return doc;
}


QString ImportWidget::cubeNameFromReader()
{
	QString name = reader.fileName();
	name = name.mid(name.lastIndexOf("/")+1,name.lastIndexOf(".")-name.lastIndexOf("/")-1);
	return name;
}

QString ImportWidget::cubeName()
{
	return editCubeName->text();
}

QStringList ImportWidget::insertsList()
{
	reader.first();
	QStringList inserts;
	//inserts << QString("set current database \"%1\"").arg(cubeName());
	int start = 1;
	if(cbFirstAsSepCrd->checkState()==Qt::Checked) start=0;
	while(reader.next()){
		inserts << reader.createInsert(start,cubeName());
	}
	return inserts;
}

QString ImportWidget::inserts()
{
	return insertsList().join(";\n");
}

void ImportWidget::insertsInNewWindow()
{
	
	emit openQueryWindow(inserts());	
}


void ImportWidget::insertsInFile()
{
	QString fname = QFileDialog::getSaveFileName(this,trUtf8("Сохранить"),"",STRUCT_PROJ_FILENAME_FILTER);
	if(fname.isEmpty()) return;
	
	QFile file(fname);
	if(!file.open(QIODevice::WriteOnly)){
		QMessageBox::warning(this,trUtf8("Ошибка"),trUtf8("Не могу открыть файл для записи '%1'").arg(file.fileName()));
		return;
	}
	file.write(inserts().toUtf8());
	file.close();
	labInfo->setText(trUtf8("сохранено"));
}

void ImportWidget::insertsInServer()
{
	if(_dbase==0) return;
	QStringList inserts = insertsList();
	QTime time;
	time.start();
	foreach(QString insert,inserts){
		_dbase->exec(insert);
	}
	labInfo->setText(trUtf8("Готово. Всего запросов: %1. Время выполнения: %2. Среднее время на запрос: %3").arg(inserts.count()).arg(time.elapsed()).arg(time.elapsed()/inserts.count()));
}

void ImportWidget::setDatabase(UMSDatabase *dbase)
{
	_dbase = dbase;
}
